<?php

namespace backend\controllers;

use common\components\Upload;
use common\models\Document;
use Yii;
use common\models\category;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * CategoryController implements the CRUD actions for category model.
 */
class CategoryController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all category models.
	 * @param int $pid
     * @return mixed
     */
    public function actionIndex($pid = 0)
    {
        $dataProvider = new ActiveDataProvider([
            'query' => category::find()->where(['status' => 1, 'pid' => $pid]),
        ]);

		Yii::$app->view->params['titles'] = '分类列表';
        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Creates a new category model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new category();

        if ($model->load(Yii::$app->request->post())) {
			if ($_FILES['Category']['error']['image'] === 0) {
				$model->image = Upload::uploadImage($model, 'image');
			}
			if ($model->save()) {
				Yii::$app->session->setFlash('success', '新增成功');
			} else {
				Yii::$app->session->setFlash('error', '新增失败');
			}

            return $this->redirect(['index']);
        } else {
			$model->pid = $_GET['id'] ? $_GET['id'] : ''; // 默认选择上级菜单

			$cateList = $model->getCateList();
			Yii::$app->view->params['titles'] = '新增分类';
            return $this->render('create', [
                'model' => $model,
				'cateList' => $cateList
            ]);
        }
    }

    /**
     * Updates an existing category model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
			if ($_FILES['Category']['error']['image'] === 0) {
				$model->image = Upload::uploadImage($model, 'image');
			}
			if ($model->save()) {
				Yii::$app->session->setFlash('success', '编辑成功');
			} else {
				Yii::$app->session->setFlash('error', '编辑失败');
			}

			Yii::$app->session->setFlash('success', '编辑成功');
            return $this->redirect(['index']);
        } else {
			$cateList = (new Category())->getCateList($id);
			Yii::$app->view->params['titles'] = '编辑分类';
            return $this->render('update', [
                'model' => $model,
				'cateList' => $cateList
            ]);
        }
    }

    /**
     * Deletes an existing category model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
		// 检测当前分类下是否有子分类
		if (Category::find()->where('pid = :pid', [':pid' => $id])->one()) {

			Yii::$app->session->setFlash('error', '删除失败！请先删除下面的子分类');
			return $this->redirect(['index']);
		}
		// 检测当前分类下是否有文章
		if (Document::find()->where('category_id = :id', [':id' => $id])->one()) {

			Yii::$app->session->setFlash('error', '删除失败！请先删除当前分类下的文章');
			return $this->redirect(['index']);
		}

        $this->findModel($id)->delete();
		Yii::$app->session->setFlash('success', '删除成功');
        return $this->redirect(['index']);
    }

    /**
     * Finds the category model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return category the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = category::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
